//
//  DemoView.swift
//  Encrypto VPN
//
//  Created by 周波 on 2024/7/2.
//

import SwiftUI

struct DemoView: View {
    @State private var beforeSelectedLanguage = "English"
    @State private var afterSelectedLanguage = "Chinese"
    var body: some View {
        
        InputView(beforeSelectedLanguage: $beforeSelectedLanguage,
                  afterSelectedLanguage: $afterSelectedLanguage)
        
    }
}

#Preview {
    DemoView()
}

struct InputView: View {
    @State private var text: String = ""
    @State var isTeanslate = false
    @State var dataId: Int = -1
    @Binding var beforeSelectedLanguage: String
    @Binding var afterSelectedLanguage: String
    @FocusState private var isTextEditorFocused: Bool
   // @StateObject private var adManager = InterstitialAdManager()
    
    var body: some View {
        VStack {
            RoundedRectangle(cornerRadius: 10)
                .strokeBorder(Color.blue, lineWidth: 2)
                .foregroundColor(Color("title"))
                .background(Color("title"))
                .frame(height: 220)
                .overlay(
                    VStack {
                        TextEditor(text: $text)
                            .focused($isTextEditorFocused)
                            .foregroundColor(Color("title"))
                            .background(Color("title"))
                            .cornerRadius(10)
                            .padding(.bottom, 20)
                            .onChange(of: text) { newValue in
                                if newValue.hasSuffix("\n") {
                                    self.text = newValue.trimmingCharacters(in: .whitespacesAndNewlines)
                                    isTextEditorFocused = false
                                    
                                    //adManager.showInterstitial()
                                    let requestText = "translate \(text) into \(afterSelectedLanguage) And only return the translated string without any additional characters"
                                    postRequest(with: requestText) { result in
                                        switch result {
                                        case .success(let responseString):
                                            self.dataId = DatabaseManager.shared.insertTranslation(beforeLanguage: beforeSelectedLanguage, afterLanguage: afterSelectedLanguage, beforeText: self.text, afterText: responseString, isFavorite: false)
                                            
                                         
                                            
                                            // 确保 dataId 更新后才触发导航
                                            if self.dataId != -1 {
                                                self.isTeanslate = true
                                            }
                                        case .failure(let error):
                                            print("Error: \(error)")
                                        }
                                    }
                                }
                            }
                            .frame(maxHeight: .infinity)
                            .onTapGesture {
                                UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
                            }
                        
                        Spacer()
                    }
                        .padding(5)
                )
                .overlay(
                    VStack {
                        Spacer()
                        HStack {
                            Spacer()
                            HStack(spacing: 10) {
                                Image("voice")
                                    .onTapGesture {
                                        print("click a voice: \(text)")
                                        speak(text: text, language: "zh-CN")
                                    }
                                
                                Image("copy")
                                    .onTapGesture {
                                        writeToClipboard(text: text)
                                    }
                                
                                Button(action:{
                                    isTextEditorFocused = false
                                    
                                    //adManager.showInterstitial()
                                    let requestText = "translate \(text) into \(afterSelectedLanguage) And only return the translated string without any additional characters"
                                    postRequest(with: requestText) { result in
                                        switch result {
                                        case .success(let responseString):
                                            self.dataId = DatabaseManager.shared.insertTranslation(beforeLanguage: beforeSelectedLanguage, afterLanguage: afterSelectedLanguage, beforeText: self.text, afterText: responseString, isFavorite: false)
                                            
                                            
                                            // 确保 dataId 更新后才触发导航
                                            if self.dataId != -1 {
                                                self.isTeanslate = true
                                            }
                                        case .failure(let error):
                                            print("Error: \(error)")
                                        }
                                    }
                                }){
                                    Text("translate")
                                    
                                }
                                
                                
                                
                            }
                            .padding(5)
                        }
                    }
                )
            
            NavigationLink(destination: TranslateView(id: Int64(dataId)), isActive: $isTeanslate) {
                EmptyView()
            }
            .hidden()
            Spacer()
        }
        .frame(height: 220)
        
        
        .padding()
    }
}
